package com.communal.dao.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.communal.dao.IModelDao;
import com.communal.model.Model;
import com.communal.util.AppConstants;

/**
 * Implements DAO methods for model
 * @author Andrey
 */
@Repository
public class ModelDao extends BaseDao implements IModelDao{

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public <T> List<T> getEnabledEntitiesByModel(Model p_model, Class p_class) {
		DetachedCriteria criteria = DetachedCriteria.forClass(p_class)
		.add(Restrictions.eq(PROPERTY_MODEL, p_model))
		.add(Restrictions.eq(PROPERTY_ENABLED, AppConstants.ENTITY_STATE_ENABLED))
		.addOrder(Order.asc(PROPERTY_ID));
		return hibernateTemplate.findByCriteria(criteria);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Long getEnabledEntitiesCountByModel(Class p_class, Model p_model) {
		DetachedCriteria criteria = DetachedCriteria.forClass(p_class)
		.setProjection(Projections.count( PROPERTY_ID ))
		.add(Restrictions.eq(PROPERTY_ENABLED, AppConstants.ENTITY_STATE_ENABLED))
		.add(Restrictions.eq(PROPERTY_MODEL, p_model));
		List<Long> countList = hibernateTemplate.findByCriteria(criteria);
		if(CollectionUtils.isNotEmpty(countList)){
			return countList.get(0) != null ? countList.get(0) : 0L; 
		}else{
			return 0L;
		}
	}
}
